package com.zy.imagineCommunity.webSocket;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 张宇
 * @date 2021/6/9 11:44
 */
@Component
public class MessageHandler extends TextWebSocketHandler {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final Map<Long, WebSocketSession> SESSIONS = new HashMap<>();

    @Override
    public void handleTextMessage(WebSocketSession webSocketSession, TextMessage textMessage) throws Exception {
        Long uid = (Long) webSocketSession.getAttributes().get("uid");

//      JsonNode jsonNode = MAPPER.readTree(message.getPayload());
//      Long toId = jsonNode.get("toId").asLong();
//      String msg = jsonNode.get("msg").asText();

//      toId=1&msg=你好
        String[] message = (textMessage.getPayload()).split("&");
        String[] toIdString = message[0].split("=");
        Long toId = Long.parseLong(toIdString[1]);
        String[] msgString = message[1].split("=");
        String msg = msgString[1];

        //判断to用户是否在线
        WebSocketSession toSession = SESSIONS.get(toId);
        if (toSession != null && toSession.isOpen()) {
            //具体格式需要和前端对接
            toSession.sendMessage(new TextMessage(msg));
        }

    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Long uid = (Long) session.getAttributes().get("uid");
        //将当前用户的session放置到map中，后面会使用相应的session通信
        SESSIONS.put(uid, session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接已经断开!");
    }

}
